<template>
  <div class="box">
    <el-tree
      :data="data"
      :props="defaultProps"
      show-checkbox
      node-key="layerCode"
      default-expand-all
      backgroundColor="#000"
      @check-change="handleCheckChange"
      ref="treeol"
    >
      <template #default="{ node, data }">
        <div class="ric">
          <span :class="{ 'text-color-change': node.checked }">{{ data.layerName }}</span>
          <!-- <span v-if="data.layerTableChart"><i class="bgicon"></i></span> -->
        </div>
      </template>
    </el-tree>
  </div>

  <teleport to="body">
    <div ref="popup" class="popup">
      <div class="namecenter" v-show="searchpoitype == 2">{{ poiname }}</div>
      <autoDialog
        :isuseDraggable="false"
        size="small"
        :title="poiname"
        :isFixed="false"
        @close="clearFlag"
        v-show="searchpoitype == 1"
      >
        <div v-if="earthQuakeType == 2">
          <div class="title"
            >发震时刻&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.time }}</span></div
          >
          <div class="title"
            >位置&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.macroscopic }}</span></div
          >
          <div class="title"
            >震级&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.shockLevel }}级</span></div
          >
          <div class="title"
            >经度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.location[0] }}</span></div
          >
          <div class="title"
            >纬度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.location[1] }}</span></div
          >
        </div>
        <div v-else>
          <div style="height: 100%; line-height: 30px; font-size: 18px">
            <div class="title"
              >发震时刻&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.time }}</span></div
            >
            <div class="title"
              >位置&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.macroscopic }}</span></div
            >
            <div class="title"
              >经度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.location[0] }}</span></div
            >
            <div class="title"
              >纬度&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.location[1] }}</span></div
            >
            <div class="title"
              >震级&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.shockLevel }}级</span></div
            >
            <div class="title"
              >死亡人数&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.die }}人</span></div
            >
            <div class="title"
              >受伤人数&nbsp;:&nbsp;<span class="desc">{{ earthQuakeInfo.injured }}人</span></div
            >
            <div class="title"
              >经济损失&nbsp;:&nbsp;<span class="desc"
                >{{ earthQuakeInfo.economics }}万元</span
              ></div
            >
          </div>
        </div>
      </autoDialog>
    </div>
  </teleport>
</template>
  
  <script setup>
import { getSysMapLayerList } from '../../../../api/sysmaplayer.js'
import { onMounted } from 'vue'
import { loadWmsMap, delWmsMap, clearLayerFlag } from '../../../../api/gis3d/maputils'
import { useMapStoreStore } from '../../../../stores/index'
import dayjs from 'dayjs'
import {
  loadEarthQuakeYXC,
  delEarthQuakeYXC,
  mimeMap,
  layerFlag
} from '../../../../api/gis3d/maputils'
const data = ref([])
const store = useMapStoreStore()
const defaultProps = {
  children: 'children',
  label: 'layerName'
}

const earthQuakeType = ref(-1)

const getData = async () => {
  getSysMapLayerList().then((res) => {
    var newRes = res.filter((e) => !e.statu)
    data.value = newRes
    nextTick(() => {
      treeol.value.setCheckedKeys(['kspgyxcx'])
    })
  })
}

const treeol = ref()
let oldLaycode = []

watch(
  () => store.layerData,
  (newval) => {
    var newarrs = []
    treeol.value.getCheckedNodes().forEach((element) => {
      if (element.children.length == 0) {
        newarrs.push(element.layerCode)
      }
    })

    var newarr = []
    for (const element of newarrs) {
      var index = oldLaycode.indexOf(element)
      if (index > -1) {
        continue
      }
      newarr.push(element)
    }
    treeol.value.setCheckedKeys([...newarr, ...newval])
    oldLaycode = newval
  }
)

const handleCheckChange = (data, checked) => {
  const { layerUrl, layerCode, id, memo } = data
  if (checked) {
    if (layerUrl) {
      var index = layerUrl.indexOf(',')
      if (index > -1) {
        var urlArr = layerUrl.split(',')
        var i = 0
        for (const item of urlArr) {
          loadWmsMap(
            item,
            layerCode + i,
            store.earthquakeInfo.id,
            memo,
            store.earthquakeInfo.version
          )
          i++
        }
      } else {
        loadWmsMap(layerUrl, layerCode, store.earthquakeInfo.id, memo, store.earthquakeInfo.version)
      }
      store.addTree(layerCode)
      // store.addLayer3d(layerUrl)
    }
  } else {
    if (layerUrl) {
      var index = layerUrl.indexOf(',')
      if (index > -1) {
        var urlArr = layerUrl.split(',')
        var i = 0
        for (const item of urlArr) {
          delWmsMap(layerCode + i)
          i++
        }
      } else {
        delWmsMap(layerCode)
      }

      store.delTree(layerCode)
      // delMapLayer(layerCode)
    }
  }
}

// 将笛卡尔坐标转换为经纬度坐标数组（方便后续计算BBOX等使用）
function cartesianToLatLonArray(cartesian) {
  const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
  const longitude = Cesium.Math.toDegrees(cartographic.longitude)
  const latitude = Cesium.Math.toDegrees(cartographic.latitude)
  return [longitude, latitude]
}

// 根据点击位置和一定的缓冲范围计算BBOX（这里的缓冲范围可以根据实际地图分辨率等情况调整）
function calculateBBOX(clickCartesian, bufferDistanceInDegrees) {
  const clickLatLon = cartesianToLatLonArray(clickCartesian)
  const minLon = clickLatLon[0] - bufferDistanceInDegrees
  const maxLon = clickLatLon[0] + bufferDistanceInDegrees
  const minLat = clickLatLon[1] - bufferDistanceInDegrees
  const maxLat = clickLatLon[1] + bufferDistanceInDegrees
  return `${minLon},${minLat},${maxLon},${maxLat}`
}

function getLevel(height) {
  if (height > 48000000) {
    return 0
  } else if (height > 24000000) {
    return 1
  } else if (height > 12000000) {
    return 2
  } else if (height > 6000000) {
    return 3
  } else if (height > 3000000) {
    return 4
  } else if (height > 1500000) {
    return 5
  } else if (height > 750000) {
    return 6
  } else if (height > 375000) {
    return 7
  } else if (height > 187500) {
    return 8
  } else if (height > 93750) {
    return 9
  } else if (height > 46875) {
    return 10
  } else if (height > 23437.5) {
    return 11
  } else if (height > 11718.75) {
    return 12
  } else if (height > 5859.38) {
    return 13
  } else if (height > 2929.69) {
    return 14
  } else if (height > 1464.84) {
    return 15
  } else if (height > 732.42) {
    return 16
  } else if (height > 366.21) {
    return 17
  } else {
    return 18
  }
}

let handler = null
const popup = ref(null)
const searchpoitype = ref(1)
const earthQuakeInfo = ref({
  time: '',
  location: [],
  die: 0,
  injured: 0,
  economics: 0
})
let position
const initEventHandler = () => {
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(function (movement) {
    clearFlag()

    const ray = viewer.camera.getPickRay(movement.position)
    const cartesian = viewer.scene.globe.pick(ray, viewer.scene)
    if (cartesian) {
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      if (cartographic) {
        var xy = new Cesium.Cartesian2()
        var alti = viewer.camera.positionCartographic.height
        var level = getLevel(alti)
        if (layerFlag['lsdz']) {
          xy = mimeMap['lsdz'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          var promise = mimeMap['lsdz'].imageryProvider.pickFeatures(
            xy.x,
            xy.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promise, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 1;
              createHistoryhDom(data)
              popup.value.style.display = 'block'
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }

        if (layerFlag['lsczdz']) {
          var xys = mimeMap['lsczdz'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          var promises = mimeMap['lsczdz'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian;
              searchpoitype.value = 1;
              viewer.scene.preRender.removeEventListener(showPopup)
              createHistoryhDom(data)
              popup.value.style.display = 'block'
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }
        if (layerFlag['zhyy']) {
          let xys = mimeMap['zhyy'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['zhyy'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }
        if (layerFlag['zkyy']) {
          let xys = mimeMap['zkyy'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['zkyy'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }

        if (layerFlag['yey']) {
          let xys = mimeMap['yey'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['yey'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }

        if (layerFlag['xx']) {
          let xys = mimeMap['xx'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['xx'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }

        if (layerFlag['zx']) {
          let xys = mimeMap['zx'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['zx'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }
        if (layerFlag['gdyx']) {
          let xys = mimeMap['gdyx'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['gdyx'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian
              viewer.scene.preRender.removeEventListener(showPopup)
              searchpoitype.value = 2
              popup.value.style.display = 'block'
              poiname.value = data[0].name
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }

          if (layerFlag['lshpfb']) {
          let xys = mimeMap['lshpfb'].imageryProvider.tilingScheme.positionToTileXY(
            cartographic,
            level,
            xy
          )
          let promises = mimeMap['lshpfb'].imageryProvider.pickFeatures(
            xys.x,
            xys.y,
            level,
            cartographic.longitude,
            cartographic.latitude
          )
          Cesium.when(promises, function (data) {
            if (data && data.length > 0) {
              position = cartesian;
              viewer.scene.preRender.removeEventListener(showPopup);
              searchpoitype.value = 2;
              popup.value.style.display = 'block';
              poiname.value = data[0].data.properties.disaster_location;
              viewer.scene.preRender.addEventListener(showPopup)
            }
          })
        }
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
const poiname = ref('')
const createHistoryhDom = (d) => {
  var data = d[0].data.properties
  poiname.value = data.macroscopic + data.shockLevel + '级地震'
  var date = dayjs(data.year + data.month + data.day + data.h + ':' + data.m).format(
    'YYYY-MM-DD HH:mm'
  )
  earthQuakeInfo.value.time = date
  earthQuakeInfo.value.location = [data.longitude, data.dimensionality]
  earthQuakeInfo.value.shockLevel = data.shockLevel
  earthQuakeInfo.value.die = Number(data.die)
  earthQuakeInfo.value.injured = Number(data.injured)
  earthQuakeInfo.value.economics = data.economics
  earthQuakeInfo.value.macroscopic = data.macroscopic
  if (data.die > 0 || data.economics > 0 || data.injured > 0) {
    earthQuakeType.value = 1
    return
  }
  earthQuakeType.value = 2
}

function showPopup() {
  var winPosi = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, position)
  if (!winPosi) return
  var x = winPosi.x
  var y = winPosi.y
  var dx = popup.value.clientWidth / 2
  var dy = popup.value.clientHeight
  popup.value.style.left = x - dx + 'px'
  popup.value.style.top = y - dy - 25 + 'px'
}

watch(
  () => store.isInitCesium,
  (n) => {
    if (n) {
      initEventHandler()
    }
  }
)

function clearFlag() {
  popup.value.style.display = 'none'
  viewer.scene.preRender.removeEventListener(showPopup)
}

onMounted(() => {
  getData()
})
onUnmounted(() => {
  handler && handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK) //移除事件
  viewer.scene.preRender.removeEventListener(showPopup)
  clearLayerFlag()
})
</script>
  
  <style lang="scss" scoped>
.namecenter {
  padding: 2px 15px;
  height: 40px;
  font-size: 22px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  color: #ffffff;
}
.popup {
  position: fixed;
  display: none; /* 初始隐藏 */
 
  .title {
    font-size: 16px;
    color: #b9eeff;
    line-height: 26px;
    span {
      color: #fff;
    }
  }
}
.el-tree-node__content {
  position: relative;
}
.disabled {
  cursor: not-allowed;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2;
}
.box {
  height: 100%;
}
.el-tree {
  background-color: transparent;
  color: #e3e3e3;
  font-size: 16px;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: transparent !important;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner:after) {
  border-color: #01c2ff;
}
:deep(.el-checkbox__inner) {
  background-color: transparent;
}
:deep(.el-tree-node__content) {
  display: flex;
  align-items: center;
}

:deep(.el-tree-node__content:hover) {
  background-color: transparent;
}
.el-tree-node:hover {
  background-color: transparent !important;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: transparent !important;
  color: #01c2ff;
}

:deep(.el-tree-node__expand-icon) {
  color: #fff;
}
.text-color-change {
  color: #01c2ff; /* 或者其他颜色 */
}
.ric {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px 0 0;
  box-sizing: border-box;
  color: #b9eeff;
}
.bgicon {
  display: inline-block;
  width: 20px;
  height: 20px;

  background-image: url(/static/assets/chart.png);
  background-size: 100% 100%;
}
</style>
  